package com.ghck.message.util;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.utils.StringUtils;

import com.ghck.message.config.JpushProperties;
import com.ghck.message.model.JPushMessage;
import com.ghck.message.model.JPushNotification;
import com.ghck.message.model.JPushPlatform;
import com.google.gson.JsonObject;

public class PushUtil {
	
	private static Logger logger = LoggerFactory.getLogger(PushUtil.class);
	
	static{
		ClientConfig config = ClientConfig.getInstance();
		config.setMaxRetryTimes(3);
	}
	
	
	/***
	 * 根据别名推送
	 * @param noticfication
	 */
	public static void sendNotification(JPushNotification noticfication){
		Integer appId=noticfication.getAppId();
		Builder builder = PushPayload.newBuilder();

		JPushClient jpushClient=getJpushClientAuthFromAppId(appId);
		if(jpushClient==null){
			logger.error("生成jpushClient失败，appId is {}",appId);
			return;
		}
		builder.setAudience(Audience.all());
		/**
		if(StringUtils.isNotEmpty(noticfication.getAlias())){
//			builder.setAudience(Audience.alias(noticfication.getAlias()));
			builder.setAudience(Audience.registrationId(noticfication.getAlias()));
		}else if(CollectionUtils.isNotEmpty(noticfication.getAliases())){
			builder.setAudience(Audience.alias(noticfication.getAliases()));
//			builder.setAudience(Audience.registrationId(noticfication.getAliases()));
		}else{
			logger.error("alias is illegal,alias is {},aliases is {}",noticfication.getAlias(),noticfication.getAliases());
			return;
		}**/
		
		logger.info("alias is {},aliases is {}",noticfication.getAlias(),noticfication.getAliases());
		
		switch(noticfication.getPlatform()){
		case JPushPlatform.ios:
			builder.setPlatform(Platform.ios());
			break;
		case JPushPlatform.android:
			builder.setPlatform(Platform.android());
			break;
		case JPushPlatform.android_ios:
			builder.setPlatform(Platform.android_ios());
			break;
		}
		Notification.Builder notificationBulder = Notification.newBuilder();
		if((noticfication.getPlatform() & JPushPlatform.ios) == JPushPlatform.ios){
			IosNotification.Builder iosNotificationBuilder = IosNotification.newBuilder().setAlert(noticfication.getAlert()).setSound("default").incrBadge(1);
			if(noticfication.getExtras()!=null){
				for(Entry<String, Object> entry : noticfication.getExtras().entrySet()){
					iosNotificationBuilder.addExtra(entry.getKey(), entry.getValue().toString());
				}
			}
			notificationBulder.addPlatformNotification(iosNotificationBuilder.build());
		}
		if((noticfication.getPlatform() & JPushPlatform.android) == JPushPlatform.android){
			AndroidNotification.Builder androidNotificationBuilder = AndroidNotification.newBuilder();
			androidNotificationBuilder.setTitle(noticfication.getTitle()).setAlert(noticfication.getAlert());
			if(noticfication.getExtras()!=null){
				for(Entry<String, Object> entry : noticfication.getExtras().entrySet()){
					androidNotificationBuilder.addExtra(entry.getKey(), entry.getValue().toString());
				}
			}
			notificationBulder.addPlatformNotification(androidNotificationBuilder.build());
		}
		builder.setNotification(notificationBulder.build());

		Options.Builder optionsBuilder = Options.newBuilder();
		if(noticfication.getSendno()!=null){
			optionsBuilder.setSendno(noticfication.getSendno());
		}
		optionsBuilder.setTimeToLive(86400);
		optionsBuilder.setApnsProduction("1".equals(ConfigUtil.getApns("flag"))?true:false);
		builder.setOptions(optionsBuilder.build());

		push2JG(builder.build(),jpushClient);

	}

	/***
	 * 根据别名发送自定义消息
	 * @param message
	 */
	
	public static void sendMessage(JPushMessage message){
		//TODO valid message
		Integer[] appIds=message.getAppIds();
		
		for(int i=0;i<appIds.length;i++){
			Builder builder = PushPayload.newBuilder();
			Integer appId=appIds[i];
			JPushClient jpushClient=getJpushClientAuthFromAppId(appId);
			if(jpushClient==null){
				logger.error("生成jpushClient失败，appId is {}",appId);
				continue;
			}

			if(message.getAlias() != null){
				builder.setAudience(Audience.alias(message.getAlias()));
			}else if(CollectionUtils.isNotEmpty(message.getAliases())){
				builder.setAudience(Audience.alias(message.getAliases()));
			}
			builder.setAudience(Audience.alias(message.getAlias()));
			switch(message.getPlatform()){
			case JPushPlatform.ios:
				builder.setPlatform(Platform.ios());
				break;
			case JPushPlatform.android:
				builder.setPlatform(Platform.android());
				break;
			case JPushPlatform.android_ios:
				builder.setPlatform(Platform.android_ios());
				break;
			}

			cn.jpush.api.push.model.Message.Builder messageBuilder=Message.newBuilder();
			messageBuilder.setTitle(message.getTitle());
			if(!StringUtils.isTrimedEmpty(message.getMsgContent())){
				messageBuilder.setMsgContent(message.getMsgContent());
			}
			if(message.getContentType()!=null){
				messageBuilder.setContentType(message.getContentType().toString());
			}
			 Map<String, Object> extras = message.getExtras();
			if(extras!=null){
				for(Entry<String, Object> entry : extras.entrySet()){
					Object object =  entry.getValue();
					if(object instanceof Number){
						messageBuilder.addExtra(entry.getKey(),(Number)object);
					}else if(object instanceof Boolean){
						messageBuilder.addExtra(entry.getKey(),(Boolean)object);
					}else if(object!=null){
						messageBuilder.addExtra(entry.getKey(),object.toString());
					}
				}
			}

			builder.setMessage(messageBuilder.build());

			Options.Builder optionsBuilder = Options.newBuilder();
			if(message.getSendno()!=null){
				optionsBuilder.setSendno(message.getSendno());
			}
			optionsBuilder.setTimeToLive(86400);
			optionsBuilder.setApnsProduction("1".equals(ConfigUtil.getApns("flag"))?true:false);
			builder.setOptions(optionsBuilder.build());

			push2JG(builder.build(),jpushClient);	
		}
		

	}
	
	public static JsonObject push2JG(PushPayload payLoad,JPushClient jpushClient){
		logger.info("push2JG,payLoad is {}",payLoad);
		JsonObject obj = new JsonObject();
		PushResult result = null;
		try {
			result = jpushClient.sendPush(payLoad);
			logger.info("极光返回是{}",result);
		} catch (APIConnectionException | APIRequestException e) {
			logger.error("发送失败，原因是{}",e.getMessage());
			e.printStackTrace();
		}
		logger.info("极光返回结果是result:"+result);
		if(result!=null){
			obj.addProperty("code",result.getResponseCode());
			obj.addProperty("sendno", result.sendno);
		}
		return obj;
	};
	
	private static JPushClient getJpushClientAuthFromAppId(Integer appId) {
		if(appId==null||appId<=0){
			return null;
		}
		String keyAndSecret=ConfigUtil.getKeyAndSecret(appId);
		if(StringUtils.isTrimedEmpty(keyAndSecret)){
			return null;
		}
		String[] param=keyAndSecret.split("\\|");
		if(param.length!=2){
			return null;
		}
		logger.info("appkey is {}",param[0]);
		JPushClient client=new JPushClient(param[1],param[0]);
		return client;
	}
	
	public static JsonObject sendBroadCast(JPushNotification noticfication){

		Builder builder = PushPayload.newBuilder();
		Integer appId=noticfication.getAppId();
		JPushClient jpushClient=getJpushClientAuthFromAppId(appId);
		if(jpushClient==null){
			logger.error("PushUtil:生成jpushClient失败，appId is {}",appId);
			return null;
		}

		builder.setAudience(Audience.all());
		switch(noticfication.getPlatform()){
		case JPushPlatform.ios:
			builder.setPlatform(Platform.ios());
			break;
		case JPushPlatform.android:
			builder.setPlatform(Platform.android());
			break;
		case JPushPlatform.android_ios:
			builder.setPlatform(Platform.android_ios());
			break;
		}
		Notification.Builder notificationBulder = Notification.newBuilder();
		if((noticfication.getPlatform() & JPushPlatform.ios) == JPushPlatform.ios){
			IosNotification.Builder iosNotificationBuilder = IosNotification.newBuilder().setAlert(noticfication.getAlert()).setSound("default").incrBadge(1);
			if(noticfication.getExtras()!=null){
				for(Entry<String, Object> entry : noticfication.getExtras().entrySet()){
					iosNotificationBuilder.addExtra(entry.getKey(), entry.getValue().toString());
				}
			}
			notificationBulder.addPlatformNotification(iosNotificationBuilder.build());
		}
		if((noticfication.getPlatform() & JPushPlatform.android) == JPushPlatform.android){
			AndroidNotification.Builder androidNotificationBuilder = AndroidNotification.newBuilder();
			androidNotificationBuilder.setTitle(noticfication.getTitle()).setAlert(noticfication.getAlert());
			if(noticfication.getExtras()!=null){
				for(Entry<String, Object> entry : noticfication.getExtras().entrySet()){
					androidNotificationBuilder.addExtra(entry.getKey(), entry.getValue().toString());
				}
			}
			notificationBulder.addPlatformNotification(androidNotificationBuilder.build());
		}
		builder.setNotification(notificationBulder.build());

		Options.Builder optionsBuilder = Options.newBuilder();
		if(noticfication.getSendno()!=null){
			optionsBuilder.setSendno(noticfication.getSendno());
		}
		optionsBuilder.setTimeToLive(86400);
		optionsBuilder.setApnsProduction("1".equals(ConfigUtil.getApns("flag"))?true:false);
		builder.setOptions(optionsBuilder.build());

		return push2JG(builder.build(),jpushClient);
	}
	
}
